package com.csx.base.concurrency.container;


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p> what does this class do ? </p>
 *   该案例是 ConcurrentHashMap的使用案例,主要包括 ConcurrentHashMap的
 *   1. 增加/修改 put,computeIfAbsent
 *   2. 查询 get/forEach
 *   3. 删除 remove
 *
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/12/6 周五 8:46
 */
public class ConcurrentHashMapTest {

    private final ConcurrentHashMap<String, String>  concurrentHashMap = new ConcurrentHashMap<>();

    /**
     * 一、 ConcurrentHashMap 核心原理
     * <p> 1.1 put 方法的核心原理
     * <p> 1.2 computeIfAbsent 方法核心原理
     * <p> 1.3 get 方法核心原理
     * <p> 1.4 forEach 方法核心原理
     * <p> 1.5 remove 方法核心原理
     */
    public void test() {

        // 1. 增加/修改
        concurrentHashMap.putIfAbsent("key1","value1");
        new Thread(()-> {
            concurrentHashMap.computeIfAbsent("test", (d) -> {
                try {
                    TimeUnit.SECONDS.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return "test";
            });
        }).start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        concurrentHashMap.computeIfAbsent("key2", k -> "value2");
        concurrentHashMap.put("key1", "valueOne");

        // 2.查询
        concurrentHashMap.get("key1");
        concurrentHashMap.forEach((k,v) -> {
            System.out.println(k + " -> " + v);
        });

        // 3. 删除
        concurrentHashMap.remove("key1");





    }

    public static void main(String[] args) {
        ConcurrentHashMapTest concurrentHashMapTest = new ConcurrentHashMapTest();
        concurrentHashMapTest.test();

    }



}
